#include "ring_queue.hpp"
#include "Task.hpp"
#include <pthread.h>
#include <ctime>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>

std::string SelfName()
{
    char name[128];
    snprintf(name, sizeof(name), "thread[0x%x]", pthread_self());
    return name;
}

void *ProductorPoutine(void *rq)
{
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while (true)
    {
        sleep(2);
        int x = rand() % 10;
        int y = rand() % 5;
        char op = oper[rand() % oper.size()];
        // 将构建的随机数放入任务当中
        Task t(x, y, op, mymath);
        // 生产任务
        ringqueue->Push(t);
        // 输出提示
        std::cout << SelfName() << ",生产者派发了一个任务:" << t.toTaskString() << std::endl;
    }
}

void *ConsumerRoutine(void *rq)
{
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while (true)
    {
        // sleep(2);
        Task t;
        // 消费任务
        ringqueue->Pop(&t);
        std::string result = t();
        std::cout << SelfName() << ",消费者消费了一个任务:" << result << std::endl;
    }
}

int main()
{
    // 随机数种子
    srand((unsigned int)time(nullptr) ^ getpid() ^ pthread_self()); // 足够随机
    RingQueue<Task> *rq = new RingQueue<Task>();                    // 构建生产者-消费者队列

    pthread_t p[2], c[2];
    for (int i = 0; i < 2; i++)
        pthread_create(p + i, nullptr, ProductorPoutine, rq);
    for (int i = 0; i < 2; i++)
        pthread_create(c + i, nullptr, ConsumerRoutine, rq);

    for (int i = 0; i < 2; i++)
        pthread_join(p[i], nullptr);
    for (int i = 0; i < 2; i++)
        pthread_join(c[i], nullptr);

    delete rq;
    return 0;
}